package hn.cch.feature.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

public class ReflectDemo {

    public static void main(String[] args) {

        try {
            Class<ReflectClass> clazz = ReflectClass.class;
            // Class<ReflectClass> clazz = Class.forName("hn.cch.grammar.jdk.ReflectClass");

            // 构造函数
            // Constructor<?>[] constructors = clazz.getConstructors(); // public
            Constructor<?>[] constructors = clazz.getDeclaredConstructors();
            Arrays.stream(constructors).forEach(p -> p.setAccessible(true));

            // 默认无参构造函数
            // ReflectClass reflectClass = clazz.newInstance();

            // 构造函数
            Constructor<ReflectClass> constructor = clazz.getConstructor(String.class, String.class);
            ReflectClass reflectClass = constructor.newInstance("field0", "field1");

            // 属性
            // Field[] fields = clazz.getFields();  // public
            Field[] fields = clazz.getDeclaredFields();
            Arrays.stream(fields).forEach(p -> p.setAccessible(true));

            Field field = clazz.getField("field");
            field.set(reflectClass, "field");
            System.out.println(field.get(reflectClass));

            // 方法
            // Method[] methods = clazz.getMethods(); // public
            Method[] methods = clazz.getDeclaredMethods();
            Arrays.stream(methods).forEach(p -> p.setAccessible(true));

            Method method = clazz.getMethod("method", String.class);
            System.out.println(method.invoke(reflectClass, "method"));

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
